package com.lql.lqlreader.service.subscriber

import com.lql.lqlreader.service.exception.HttpResultException
import com.lql.lqlreader.service.entity.HttpResultEntity
import rx.Subscriber
import timber.log.Timber
import java.net.ConnectException
import java.net.SocketException
import java.util.concurrent.TimeoutException

abstract class HttpResultSubscriber<T> : Subscriber<HttpResultEntity<T>>() {
    override fun onNext(httpResult: HttpResultEntity<T>) {
        httpResult.takeIf { it.isSuccess }?.also { onSuccess(httpResult.data) }?: _onError(httpResult.errorCode, "")
    }

    abstract fun _onError(status: Int, msg: String?)

    abstract fun onSuccess(data: T?)

    override fun onError(throwable: Throwable?) {
        var code = -1000
        var msg: String? = null
        // 如果出现异常，设置异常编号
        if (throwable is ConnectException || throwable is SocketException || throwable is TimeoutException) {
            code = -9999
            msg = "network anomaly"
        } else if (throwable is HttpResultException) {
            code = throwable.code
            msg = throwable.msg
        }
        Timber.e("Request to enter the onError of HttpResultSubscriber, status is %s , msg is %s ", code, msg)
        _onError(code, msg)
        onCompleted()
    }

    override fun onCompleted() {  Timber.d(" ----------------> onCompleted")  }
}